package com.core.reach.oauth2server.service.impl;

import com.core.reach.oauth2server.domain.ClientInfo;
import com.core.reach.oauth2server.service.ClientInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;

/**
 * @author Mr_zhangmu
 * @version V1.0
 * @description: TODO
 * @date 2020/6/19 15:59
 **/
@Slf4j
@Service("myClientDetailsService")
public class MyClientDetailsServiceImpl implements ClientDetailsService {

    @Resource
    private ClientInfoService clientInfoService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        log.info("clientId:{}", clientId);
        //通过clientId查询客户端信息
        ClientInfo client = clientInfoService.findByClientId(clientId);
        if (client == null) {
            //返回的错误信息
            throw new ClientRegistrationException("clientId无效");
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        //设置clientID
        clientDetails.setClientId(client.getClientId());
        //设置clientSecret
        clientDetails.setClientSecret(client.getClientSecret());
        //设置多个跳转的URL地址
        clientDetails.setRegisteredRedirectUri(new HashSet<>(Arrays.asList(client.getRedirectUri().split(","))));
        //设置授权类型
        clientDetails.setAuthorizedGrantTypes(Arrays.asList(client.getAuthorizedGrantTypes().split(",")));
        //设置scope范围列表
        clientDetails.setScope(Arrays.asList(client.getScopes().split(",")));

        return clientDetails;
    }

}
